package com.os.osframe.scaffold.create;

import com.os.osframe.scaffold.util.Native2Ascii;
import com.os.osframe.scaffold.domain.ScaffoldXmlField;
import com.os.osframe.scaffold.domain.ScaffoldXmlTable;
import com.os.osframe.scaffold.util.PropertyConfigurerLoader;
import com.os.osframe.util.StringUtil;

import javax.annotation.Resource;
import java.io.*;
import java.util.List;

/**
 * Created by wangdc on 2015-4-27.
 */
public class CreateResCode extends BaseCreate implements ICreateCode {
    public CreateResCode(){

    }
    protected List<ScaffoldXmlTable> scaffoldXmlTableList;
    public CreateResCode(List<ScaffoldXmlTable> scaffoldXmlTableList){
        this.scaffoldXmlTableList=scaffoldXmlTableList;
    }
    public void create(String packages)throws Exception{
        System.out.println("=====开始生成资源文件====");
        //String path = replaceStr(new File("").getAbsolutePath(), "\\", "/");//获取项目的根路径，这里获取到的是softdp的路径
        String basePath = (String) getPropertyConfigurer().getProperty("osframe.file.path");//获取属性配置的服务器路径
        if (basePath.substring(basePath.length() - 1).equals("/")) {
            basePath = basePath.substring(basePath.length() - 1);
        }
        //System.out.println(path);//E:/java/intelijwork/softdp
        String targetFilePath=basePath;
        targetFilePath+="/auto/code/"+packages.replaceAll("\\.","/")+"/resources";
        //System.out.println(targetFilePath);
        String tempPath = replaceStr(new File(this.getClass().getResource("").getPath()).getAbsolutePath(),"\\","/");//获取当前类所在路径
        if(tempPath.indexOf("create")>-1){
            tempPath=tempPath.substring(0,tempPath.length()-7);
        }
        tempPath+="/resources";
        //System.out.println(tempPath);
        createFile(tempPath,targetFilePath);
    }
    public void transCode(String module,String packages)throws Exception{
        System.out.println("=====开始转码资源文件====");
        String basePath = (String) getPropertyConfigurer().getProperty("osframe.file.path");//获取属性配置的服务器路径
        if (basePath.substring(basePath.length() - 1).equals("/")) {
            basePath = basePath.substring(basePath.length() - 1);
        }
        String targetFilePath=basePath;
        targetFilePath+="/code/"+packages.replaceAll("\\.","/")+"/resources/i18n";
        transCode(targetFilePath);
    }
    public void transCode(String targetFilePath)throws Exception{
        File targetFile = new File(targetFilePath);
        if (targetFile.isDirectory()) {
            String[] files = targetFile.list();
            if (files != null) {
                for (int i = 0; i < files.length; i++) {
                    if (files[i].startsWith("."))
                        continue;
                    transCode(targetFilePath + "/"+files[i]);
                }
            }
        } else {
            StringBuffer sb = new StringBuffer();
            BufferedReader input = new BufferedReader(new InputStreamReader(
                    new FileInputStream(targetFile), "UTF-8"));
            for (String s = input.readLine(); s != null; s = input.readLine()){
                sb.append(s + "\r\n");
            }
            input.close();
            BufferedWriter output = null;
            String writeStr=null;
            targetFile.createNewFile();
            output = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(targetFile), "UTF-8"));
            writeStr="\r\n"+sb.toString();
                writeStr= Native2Ascii.ascii2native(writeStr);//解码后处理
                writeStr= Native2Ascii.native2ascii(writeStr);//转换中文编码
            output.write(writeStr);
            output.close();
        }
    }
    /**
     * 待替换变量
     * @param packages 模块包路径
     */
    @Override
    protected void stringDeal(String packages){
        replaceStrings[0]="${packages}";
        replaceStrings[1]="${packageSimple}";
        replaceStrings[2]="${packagePath}";


        //获取域模型信息

        //获取包简称
        String packagesSimple=null;
        String[] packagesSimpleArr=packages.split("\\.");

        for(int i=0;i<packagesSimpleArr.length;i++){
            if(StringUtil.isNull(packagesSimple)){
                packagesSimple=packagesSimpleArr[i];
            }else{
                packagesSimple+=packagesSimpleArr[i].substring(0, 1).toUpperCase()+packagesSimpleArr[i].substring(1);
            }
        }
        targetStrings[0]=packages;
        targetStrings[1]=packagesSimple;
        targetStrings[2]=packages.replaceAll("\\.","/");

    }
    @Override
    public void createFile(String tempPath,String targetPath)throws  Exception{
        System.out.println("正在生成文件：" + tempPath + " -> " + targetPath);
        File tempFile = new File(tempPath);
        File targetFile = new File(targetPath);
        if (tempFile.isDirectory()) {
            targetFile.mkdir();
            String[] files = tempFile.list();
            if (files != null) {
                for (int i = 0; i < files.length; i++) {
                    if (files[i].startsWith("."))
                        continue;
                    createFile(tempPath + "/" + files[i], targetPath + "/"+ replaceText(files[i]));
                }
            }
        } else {
            StringBuffer sb = new StringBuffer();
            BufferedReader input = new BufferedReader(new InputStreamReader(
                    new FileInputStream(tempFile), "UTF-8"));
            for (String s = input.readLine(); s != null; s = input.readLine()){
                sb.append(s + "\r\n");
            }

            input.close();
            BufferedWriter output = null;
            String writeStr=null;
            if( i18nProp.equals(targetPath.substring(targetPath.lastIndexOf(".")+1))){//当文件存在
                if(!targetFile.exists()){
                    targetFile.createNewFile();
                    output = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(targetFile), "UTF-8"));
                }else{
                    output = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(targetFile,true), "UTF-8"));
                }
                writeStr="\r\n"+sb.toString();
                writeStr= Native2Ascii.ascii2native(writeStr);//解码后处理
                writeStr+=allI18n();
                writeStr= Native2Ascii.native2ascii(writeStr);//转换中文编码
            }else{
                targetFile.createNewFile();
                output = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(targetFile), "UTF-8"));
                writeStr=replaceText(sb.toString());
                writeStr=replaceCode(writeStr);
            }
            output.write(writeStr);
            output.close();
        }
    }

    /**
     *
     * @return
     * @throws Exception
     */
    protected String allI18n() throws Exception{
        if(scaffoldXmlTableList==null || scaffoldXmlTableList.isEmpty()){
            return "";
        }
        StringBuffer sb=new StringBuffer();
        for(int i=0;i<scaffoldXmlTableList.size();i++){
            ScaffoldXmlTable scaffoldXmlTable=scaffoldXmlTableList.get(i);
            sb.append("\r\n").append(tableI18n(scaffoldXmlTable));
        }
        return sb.toString();
    }

    /**
     * 表的中文编码信息
     * @param scaffoldXmlTable
     * @return
     * @throws Exception
     */
    protected String tableI18n(ScaffoldXmlTable scaffoldXmlTable) throws Exception{
        List<ScaffoldXmlField> scaffoldXmlFieldList =scaffoldXmlTable.getScaffoldXmlFieldList();
        StringBuffer sbEdit=new StringBuffer();
        sbEdit.append("\r\n").append(scaffoldXmlTable.getJavaName()+".module="+scaffoldXmlTable.getTableInfo());
        for(ScaffoldXmlField scaffoldXmlField : scaffoldXmlFieldList){
            sbEdit.append("\r\n").append(scaffoldXmlTable.getJavaName() + "." + scaffoldXmlField.getJavaFiledId() + "= " + scaffoldXmlField.getFiledName());
        }
        return sbEdit.toString();
    }

}
